package com.nuaa.yupicturebackend.utils;

import com.nuaa.yupicturebackend.model.entity.RedPacket;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * @Author ortonzhu
 * @Date 2025/2/23 11:58
 */
@Component
public class RedPacketUtils {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    // 生成固定大小和金额的红包，并将它们推送到 Redis 列表中
    public void generateAndPushRedPackets(List<RedPacket> redPackets, String listKey) {
        List<String> allRedPackets = new ArrayList<>();
        // 根据每个红包规格生成对应数量的红包
        for (RedPacket rp : redPackets) {
            for (int i = 0; i < rp.getCount(); i++) {
                allRedPackets.add(String.valueOf(rp.getAmount()));
            }
        }
        Collections.shuffle(allRedPackets); // 打乱红包顺序
        // 将每个红包推入 Redis 列表中
        stringRedisTemplate.opsForList().rightPushAll(listKey, allRedPackets);

    }

    // 获取一个红包金额
    public String getOneRedPacketAmount(String listKey) {
        return stringRedisTemplate.opsForList().rightPop(listKey);
    }

    // 统计剩余红包数量
    public Long countRemainingRedPackets(String listKey) {
        return stringRedisTemplate.opsForList().size(listKey);
    }

    // 检查红包列表是否为空
    public Boolean isRedPacketListEmpty(String listKey) {
        return countRemainingRedPackets(listKey) == 0;
    }

    // 统计剩余红包的具体信息并返回 List<RedPacket>
    public List<RedPacket> countRemainingRedPacketsDetailed(String listKey) {
        // 获取所有红包金额
        List<String> allRedPackets = stringRedisTemplate.opsForList().range(listKey, 0, -1);

        // 使用 Map 记录每种金额的红包数量
        Map<BigDecimal, Integer> redPacketCounts = new HashMap<>();
        assert allRedPackets != null;
        for (String amountStr : allRedPackets) {
            BigDecimal amount = new BigDecimal(amountStr);
            redPacketCounts.put(amount, redPacketCounts.getOrDefault(amount, 0) + 1);
        }

        // 构造 RedPacket 列表
        List<RedPacket> result = new ArrayList<>();
        for (Map.Entry<BigDecimal, Integer> entry : redPacketCounts.entrySet()) {
            result.add(new RedPacket(entry.getKey(), entry.getValue()));
        }

        return result;
    }
}
